/*
 * @Author: panzhiwei 749458928@qq.com
 * @Date: 2024-01-19 15:15:33
 * @LastEditors: panzhiwei 749458928@qq.com
 * @LastEditTime: 2024-02-02 11:18:59
 * @FilePath: /2DDemo/assets/Script/Arrow.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// Arrow.ts
import { _decorator, Component, Collider2D, Vec3, RigidBody2D, Vec2, Contact2DType, IPhysics2DContact, Sprite, instantiate, Prefab } from 'cc';
// import { EnemySpawner } from './EnemySpawner';
import { Enemy } from '../Enemy/Enemy';
const { ccclass, property } = _decorator;

// 原始弓箭攻击
@ccclass('Arrow')
export class Arrow extends Component {
    @property
    public attackPower: number = 50; // 弓箭的攻击力

    @property
    public shootingSpeed: number = 50; // 射击速度

    public isDestroyed: boolean = false;

    @property({ type: Prefab })
    arrow: Prefab = null;

    onLoad() {
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        console.log('onBeginContact');

        // 检查是否与敌人碰撞
        if (!this.isDestroyed && otherCollider.node.name === 'Enemy') {
            // if (selfCollider.node) {
            //     selfCollider.node.active = false;
            // }

            const sprite = selfCollider.node.getComponent(Sprite);
            if (sprite) {
                sprite.enabled = false;
            }

            setTimeout(() => {
                if (selfCollider && selfCollider.node && selfCollider.node.isValid) {
                    // selfCollider.node.active = false;
                    this.isDestroyed = true;
                    // 销毁弓箭
                    selfCollider.node.destroy();
                }


                if (otherCollider && otherCollider.node) {
                    let enemyScript = otherCollider.getComponent(Enemy);
                    if (enemyScript) {
                        let enemyPosition = otherCollider.node.position;
                        enemyScript.takeDamage(this.attackPower, enemyPosition);
                    }
                }
            }, 0);
        }
    }
}